package com.amado.course35Concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wangyl-910
 * @description 测试AtomicInteger多线程情况下数据是否异常
 * @date 2017/8/19
 * @see
 */
public class S06AtomicIntegerTest {
	static int count = 0;

	public static void main(String[] args) throws InterruptedException {
		CountDownLatch startSignal = new CountDownLatch(1);
		final AtomicInteger atomicInteger = new AtomicInteger();
		// 30线程+2，30线程 -1，结果 3000
		for (int i = 0; i < 3000; i++) {
			new Thread(new Runnable() {
				public void run() {
					try {
						startSignal.await();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					for (int j = 0; j < 100; j++) {
						atomicInteger.addAndGet(1);
						//相当于下面的count++,只不过他是线程安全的
						count++;
					}
				}
			}).start();
			// new Thread(new Runnable() {
			// public void run() {
			// for(int j=0;j<100;j++) {atomicInteger.getAndDecrement();}
			// }
			// }).start();
		}
		startSignal.countDown();
		Thread.sleep(2000);
		// 结果等于2000
		System.out.println(atomicInteger.get());
		System.out.println(count);
	}
}
